import store from '@/store';
import { HttpUtil } from '@/utils/HttpUtil';
import router from '@/router';

/**
 * @author 戴俊明 <idaijunming@163.com>
 * @description axios Token拦截器(Vuex 版)
 * @date 2019/11/21 20:47
 **/
export const tokenInterceptor = instance => {
	instance.interceptors.request.use(
		config => {
			if (store.getters.token) {
				config.headers.Authorization = store.getters.token;
			}
			return config;
		},
		error => error
	);
	instance.interceptors.response.use(
		resp => {
			if (resp.headers.upgrade === 'true') {
				console.log(resp);
				store.dispatch('account/upgrade');
			}
			return resp;
		},
		// 返回请求错误的响应
		error => {
			const resp = error.response;
			if (resp.status === 401) {
				store.commit('account/RESET_STATE');
				router.push('/login');
				return Promise.reject(new Error('用户凭证已过期，请重新登录'));
			} else {
				return Promise.reject(new Error(HttpUtil.getMessage(resp)));
			}
		}
	);
};
